package com.xinlin.framework.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class JwtTokenUtil {
    // 令牌秘钥
    @Value("${token.secret}")
    private String SECRET;
    private final long EXPIRATION = 86400L; // 24小时

    // 生成令牌（区分用户类型）
    public String generateToken(UserDetails userDetails, String userType) {
        return Jwts.builder()
            .setSubject(userDetails.getUsername())
            .claim("userType", userType) // 标识用户类型（system/app）
            .setIssuedAt(new Date())
            .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION * 1000))
            .signWith(SignatureAlgorithm.HS512, SECRET)
            .compact();
    }

    // 解析用户类型
    public String getUserTypeFromToken(String token) {
        Claims claims = Jwts.parser()
            .setSigningKey(SECRET)
            .parseClaimsJws(token)
            .getBody();
        return claims.get("userType", String.class);
    }
}
